package com.itcast.service.impl;

import com.itcast.dao.GoodDao;
import com.itcast.dao.ShoppingDao;
import com.itcast.domain.Good;
import com.itcast.domain.Shopping;
import com.itcast.service.ShoppingService;
import com.itcast.utils.ResponseBodyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service("shoppingService")
public class ShoppingServiceImpl implements ShoppingService {
    @Autowired
    private GoodDao goodDao;
    @Autowired
    private ShoppingDao shoppingDao;

    /**
     * 添加商品至购物车
     * @param id
     * @return
     */
    @Override
    public String addShop(String id) throws Exception {
        Shopping shopping = shoppingDao.findById(id);
        System.out.println(shopping);
        if (shopping == null){
            Good good = goodDao.findById(id);
            System.out.println(good);
            if (good != null){
                Shopping shopping1 = new Shopping(); //为了解决空指针异常
                shopping1.setId(good.getId());
                shopping1.setName(good.getName());
                shopping1.setPrice(good.getPrice());
                shopping1.setUrl(good.getUrl());
                shopping1.setNumber(1);
                shoppingDao.save(shopping1);
            } else {
                return ResponseBodyUtil.getUnSuccessNoObject("添加");
            }
        } else {
            shopping.setNumber(shopping.getNumber()+1);
            shoppingDao.update(shopping);
        }
        return ResponseBodyUtil.getSuccessNoObject("添加");
    }



    /**
     * 查询所有
     * @return
     */
    @Override
    public List<Shopping> findAll() {
        return shoppingDao.findAll();
    }

    @Override
    public String save(Shopping shopping) throws Exception {
        shoppingDao.save(shopping);
        return ResponseBodyUtil.getSuccess(shopping,"添加");
    }

    @Override
    public String deleteShop(String id) throws Exception {
        int count = 0;
        Shopping byId = shoppingDao.findById(id);
        if (byId != null) {
            if (byId.getNumber() > 1) {
                byId.setNumber(byId.getNumber() - 1);
                shoppingDao.update(byId);
                count = 1;
            } else {
                count = shoppingDao.deleteShop(id);
            }
        }
        if (count > 0) {
            return ResponseBodyUtil.getSuccessNoObject("删除");
        }
        return ResponseBodyUtil.getUnSuccessNoObject("删除");
    }

    @Override
    public String deleteAllShop() throws Exception {
        int count = shoppingDao.deleteAll();
        if (count > 0){
            return ResponseBodyUtil.getSuccessNoObject("删除");
        } else {
            return ResponseBodyUtil.getUnSuccessNoObject("删除");
        }
    }
}
